import 'dart:convert';
import 'package:dio/dio.dart';
import '../aes/aes_utils.dart';

/// 登录API管理类
class LoginAPI {
  static final Dio _dio = Dio();

  // 登录接口地址
  static const String _loginUrl =
      'https://api.misstory789.online/api/asf/ComicMember/Login';

  // AES加密密钥（实际项目中应该从安全的地方获取）
  static const String _aesKey = 'your-secret-key-32-characters!!';

  /// 登录请求
  /// [accountName] 账户名
  /// [password] 密码
  /// [loginType] 登录类型
  /// [platformId] 平台ID
  static Future<Map<String, dynamic>> login({
    required String accountName,
    required String password,
    String? loginType,
    int? platformId,
  }) async {
    try {
      // 构建请求参数
      final Map<String, dynamic> requestData = {
        'accountName': accountName,
        'password': password,
      };

      // 添加可选参数
      if (loginType != null) {
        requestData['loginType'] = 1;
      }
      if (platformId != null) {
        requestData['platformId'] = platformId;
      }

      print('原始请求参数: ${json.encode(requestData)}');

      // 对请求参数进行AES加密
      final String jsonData = json.encode(requestData);
      final String encryptedData = AESUtil.encryptECB(jsonData);

      // 构建加密后的请求体
      final Map<String, dynamic> encryptedRequestData = {'data': encryptedData};

      print('发送登录请求: $_loginUrl');
      print('加密后的请求参数: ${json.encode(encryptedRequestData)}');

      // 发送POST请求
      final response = await _dio.post(
        _loginUrl,
        data: encryptedData,
        options: Options(
          headers: {
            'Content-Type': 'application/json-patch+json',
            'Accept': 'application/json',
          },
          receiveTimeout: const Duration(seconds: 10),
        ),
      );

      print('响应状态码: ${response.statusCode}');
      print('原始响应数据: ${response.data}');

      // 处理响应数据
      Map<String, dynamic> responseData = response.data;

      // 如果响应也是加密的，进行解密
      if (responseData.containsKey('data') && responseData['data'] is String) {
        try {
          final String encryptedResponse = responseData['data'];
          final String decryptedResponse = AESUtil.encryptECB(
            encryptedResponse,
          );
          responseData = json.decode(decryptedResponse);
          print('解密后的响应数据: ${json.encode(responseData)}');
        } catch (decryptError) {
          print('响应解密失败: $decryptError');
          // 如果解密失败，使用原始响应数据
        }
      }

      return {
        'success': true,
        'statusCode': response.statusCode,
        'data': responseData,
        'message': '请求成功',
      };
    } on DioException catch (e) {
      print('登录请求错误: ${e.message}');
      print('错误类型: ${e.type}');
      print('响应数据: ${e.response?.data}');

      return {
        'success': false,
        'statusCode': e.response?.statusCode ?? -1,
        'data': e.response?.data,
        'message': e.message ?? '网络请求失败',
        'error': e.toString(),
      };
    } catch (e) {
      print('登录异常: $e');
      return {
        'success': false,
        'statusCode': -1,
        'data': null,
        'message': '未知错误: $e',
        'error': e.toString(),
      };
    }
  }

  /// 设置自定义AES密钥
  static String? _customAesKey;

  static void setAESKey(String key) {
    _customAesKey = key;
  }

  static String get currentAESKey => _customAesKey ?? _aesKey;

  /// 使用自定义密钥的登录方法
  static Future<Map<String, dynamic>> loginWithCustomKey({
    required String accountName,
    required String password,
    required String aesKey,
    String? loginType,
    int? platformId,
  }) async {
    final oldKey = _customAesKey;
    setAESKey(aesKey);

    try {
      final result = await login(
        accountName: accountName,
        password: password,
        loginType: loginType,
        platformId: platformId,
      );
      return result;
    } finally {
      _customAesKey = oldKey;
    }
  }
}
